package com.sgg.datastructure.stack;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Stack;

/**
 * 中缀表达式 有bug
 */
public class StackCal {
    private Stack<Integer> numStack = new Stack<>();
    private Stack<String> operateStack = new Stack<>();

    public int cal(String text) {
        //1
        char[] chars = text.toCharArray();
        for (char c : chars) {
            String value = String.valueOf(c);
            if (NumberUtil.isNumber(value)) {
                numStack.add(Integer.valueOf(value));
            } else {
                if (operateStack.isEmpty()) {
                    operateStack.push(value);
                } else {
                    //当前的操作符优先级不高于栈顶的,就要计算之前的
                    if (valueOfOperate(value) <= valueOfOperate(operateStack.peek())) {
                        Integer pop1 = numStack.pop();
                        Integer pop2 = numStack.pop();
                        Integer result = cal(pop1, pop2, operateStack.pop());
                        numStack.push(result);
                        operateStack.push(value);
                    } else {
                        operateStack.push(value);
                    }
                }
            }
        }
        System.out.println("第一轮结束======================");
        do {
            Integer pop1 = numStack.pop();
            Integer pop2 = numStack.pop();
            Integer result = cal(pop1, pop2, operateStack.pop());
            numStack.push(result);
        } while (numStack.size() != 1);
        //2
        return numStack.pop();
    }

    private Integer cal(Integer pop1, Integer pop2, String operate) {
        Integer result = null;
        switch (operate) {
            case "+":
                result = pop2 + pop1;
                break;
            case "-":
                result = pop2 - pop1;
                break;
            case "*":
                result = pop2 * pop1;
                break;
            case "/":
                result = pop2 / pop1;
                break;
        }
        if (result == null) {
            throw new RuntimeException("参数不合法");
        } else {
            System.out.printf("%d %s %d的结果为%d\n", pop2, operate, pop1, result);
            return result;
        }
    }

    public int valueOfOperate(String operate) {
        if (StrUtil.equalsAny(operate, "+")) {
            return 1;
        } else if (StrUtil.equalsAny(operate, "-")) {
            return 1;
        }else if (StrUtil.equalsAny(operate, "*", "/")) {
            return 4;
        }
        throw new RuntimeException("参数不合法");
    }


    public static void main(String[] args) {
        StackCal stackCal = new StackCal();
        String text = "9+3*2-8/4+2-7";//8
        int result = stackCal.cal(text);
        System.out.printf("%s=%d", text, result);
    }
}
